package top.yxf.spring.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import top.yxf.spring.beans.BeansException;
import top.yxf.spring.beans.PropertyValue;
import top.yxf.spring.beans.PropertyValues;
import top.yxf.spring.beans.factory.config.BeanDefinition;
import top.yxf.spring.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;

/**
 * @author xs.wu
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {

        Object bean;

        try {
            bean = createBeanInstance(beanName, beanDefinition, args);
            // 填充属性
            applyPropertyValues(beanName, beanDefinition, bean);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }
        // 添加到单例
        addSingleton(beanName, beanDefinition);
        return bean;
    }

    protected void applyPropertyValues(String beanName, BeanDefinition beanDefinition, Object bean) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                String key = propertyValue.getKey();
                Object value = propertyValue.getValue();
                if (value instanceof BeanReference) {
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                }

                BeanUtil.setFieldValue(bean, key, value);
            }
        } catch (Exception e) {
            throw new BeansException("Error setting property values：" + beanName);
        }
    }

    public Object createBeanInstance(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Constructor constructor = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructor = beanClass.getDeclaredConstructors();
        for (Constructor constructor1 : declaredConstructor) {
            if (args != null && constructor1.getParameterTypes().length == args.length) {
                constructor = constructor1;
                break;
            }
        }
        return getInstantiationStrategy().instantiate(beanDefinition, beanName, constructor, args);
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }
}
